package com.hulei.thymeleafproject;

import com.lowagie.text.pdf.BaseFont;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * @author hulei
 * @date 2024/7/27 9:26
 */

@RestController
public class TestController {

    @Resource
    private TemplateEngine templateEngineBySelf;

    @PostMapping("/printSNLabel")
    public void test(@RequestBody List<PrintSNLabelReqDTO> list) {
        list.forEach(loop -> {
            Map<String, Object> map = new HashMap<>();
            map.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            map.put("materialName", loop.getMaterialName());
            map.put("supplierName", loop.getSupplierName());
            //设备码图片二进制字节流
            BufferedImage sequencesNumberImage = BarCodeUtils.getBarCodeImage(loop.getSequencesNumber(), 100, 50);
            this.storeImage(sequencesNumberImage, "E:/111.png");
            try {
                String base64Image = BarCodeUtils.bufferedImage2Base64(sequencesNumberImage);
                System.out.println("base64Image: " + base64Image);
                map.put("sequencesNumberImage", base64Image);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            map.put("sequencesNumber", loop.getSequencesNumber());
            try {
                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                String symbolImagePath = "images/zlbcImage.png";
                InputStream inputStream = classLoader.getResourceAsStream(symbolImagePath);
                assert inputStream != null;
                BufferedImage zlbcImageBufferedImage = ImageIO.read(inputStream);
                this.storeImage(zlbcImageBufferedImage, "E:/222.png");
                String zlbcImage = BarCodeUtils.bufferedImage2Base64(zlbcImageBufferedImage);
                System.out.println("zlbcImage: " + zlbcImage);
                map.put("zlbcImage", zlbcImage);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                generateSNPicture(map);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }


    private void generateSNPicture(Map<String,Object> map) throws IOException {
        // 填充模板数据
        Context context = new Context();
        context.setVariable("createTime", map.get("createTime"));
        context.setVariable("materialName", map.get("materialName"));
        context.setVariable("supplierName", map.get("supplierName"));
        context.setVariable("sequencesNumberImage", map.get("sequencesNumberImage"));
        context.setVariable("sequencesNumber", map.get("sequencesNumber"));
        context.setVariable("zlbcImage", map.get("zlbcImage"));
        String htmlContent = templateEngineBySelf.process("printTemplate", context);
        System.out.println(htmlContent);
        htmlToPdf(htmlContent);

    }

    private void htmlToPdf(String htmlContent){
        try {
            //创建PDf文件
            ITextRenderer renderer = new ITextRenderer();
            //获取使用的字体数据（由于对中文字体显示可能会不支持，所以需要主动添加字体数据设置。）
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont("templates/fonts/simsun.ttc",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            //设置文件名称
            String sDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String sTime = new SimpleDateFormat("HHmmssSSS").format(new Date());

            // 生成临时文件
            Path tempPdfPath = Files.createTempFile("temp_pdf_"+sDate+sTime, ".pdf");
            String pdfFilePath = tempPdfPath.toAbsolutePath().toString();

            // 将html生成文档
            renderer.setDocumentFromString(htmlContent);
            renderer.layout();
            OutputStream os = new FileOutputStream(pdfFilePath);
            // 将文档写入到输出流中
            renderer.createPDF(os);
            // 关闭流
            os.close();

            //把临时生成的文件转移到E盘,这里可以根据个人需求选在把临时文件上传到文件服务器
            System.out.println("pdfFilePath: "+pdfFilePath);
            File tempPdfFile = tempPdfPath.toFile();
            System.out.println("tempPdfFileName: "+tempPdfFile.getName());
            // 复制文件到E盘
            try {
                Path targetPath = Paths.get("E:", tempPdfFile.getName()); // 目标路径
                Files.copy(tempPdfPath, targetPath);
                System.out.println("文件已复制到 E 盘");
            } catch (Exception e) {
                System.err.println("复制文件时发生错误: " + e.getMessage());
            }
            //删除临时生成的本地PDF文件
            Files.delete(tempPdfPath);
        } catch (Exception e) {
            System.out.println("生成pdf文件失败");
            throw new RuntimeException(e);
        }

    }

    private void storeImage(BufferedImage image, String filePath){
        try {
            // 指定输出文件路径和格式
            File outputFile = new File(filePath);

            // 使用 ImageIO.write 方法将图片写入磁盘
            boolean isWritten = ImageIO.write(image, "png", outputFile);

            if (isWritten) {
                System.out.println("图片已成功保存到磁盘.");
            } else {
                System.out.println("图片保存失败.");
            }
        } catch (IOException e) {
            System.err.println("保存图片时发生错误: " + e.getMessage());
        }
    }

}
